#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <sys/stat.h>
#include <fcntl.h>

#define ECHO_PORT 9999
#define BUF_SIZE 4096

int main(int argc, char* argv[]){
    // 接收3个命令 （例如：./echo_client localhost 9999）
    if (argc != 4){
        fprintf(stderr, "usage: %s <server-ip> <port>\n",argv[0]);
        return EXIT_FAILURE;
    }

    char buf[BUF_SIZE], msg[BUF_SIZE];  // 接收缓冲 发送缓冲
    int status, sock;

    // 客户端的信息
    struct addrinfo hints;
	memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_INET;          // IPv4
    hints.ai_socktype = SOCK_STREAM;    // TCP
    hints.ai_flags = AI_PASSIVE;        // 填充本地IP

    // 获取服务器的信息
    struct addrinfo *servinfo;        
    if ((status = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo error: %s \n", gai_strerror(status));
        return EXIT_FAILURE;
    }

    // 创建socket
    if((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1){
        fprintf(stderr, "Socket failed");
        return EXIT_FAILURE;
    }
    
    // 连接服务器
    if (connect (sock, servinfo->ai_addr, servinfo->ai_addrlen) == -1){
        fprintf(stderr, "Connect");
        return EXIT_FAILURE;
    }
        
    // 获取键盘输入消息 存入发送缓冲msg中
    // fgets(msg, BUF_SIZE, stdin);    

    // 获取文件中写好的HTTP请求消息
    int request_file = open(argv[3], O_RDONLY);
	if(request_file < 0) {
		printf("Failed to open the request file\n");
		return 0;
	}
    int file_len = read(request_file, msg, BUF_SIZE);

    // 向服务器发送msg中的消息
    int bytes_received;
    fprintf(stdout, "========== Sending ==========\n%s", msg);
    send(sock, msg , file_len, 0);//strlen(msg), 0);
    
    while(1){
        // 输出服务器返回的消息
        if((bytes_received = recv(sock, buf, BUF_SIZE, 0)) > 1){
            buf[bytes_received] = '\0';
            fprintf(stdout, "========== Received ==========\n%s", buf);
        }    
    }    

    // 释放资源，关闭socket
    freeaddrinfo(servinfo);
    close(sock);    
    return EXIT_SUCCESS;
}

/*
docker  run  --privileged  -it  -p 8888:9999  -v D:/2.MyFile/workspace/:/home/workspace --name Liso 15-441/641-project-1 /bin/bash
./echo_client 127.0.0.1 9999 ./cp1/sample_request_realistic

./echo_client 127.0.0.1 9999 ./cp2/request_get
*/